<template>
  <div>
    <div class="form-container">
      <el-steps simple :active="1" finish-status="success">
        <el-step title="填写基本信息"></el-step>
        <el-step title="实名认证"></el-step>
        <el-step title="业务授权"></el-step>
        <el-step title="关联对公账户"></el-step>
        <el-step title="注册成功"></el-step>
      </el-steps>
      <el-form :model="form" ref="form" label-width="220px" label-position="right" :rules="rules">
        <v-form-title title="上传证件"/>
        <el-form-item prop="certType" label="证件类型">
          <el-radio-group v-model="form.certType" @change="rules.images[0].len=form.certType+3">
            <el-radio :label="0">多证合一营业执照（统一社会信用代码）</el-radio>
            <el-radio :label="1">多证合一营业执照（存在独立的组织机构代码证号）</el-radio>
            <el-radio :label="2">普通营业执照</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="images">
          <v-unit-auth-images :images="images" v-model="form.images" @ocr="licenseOcr" @idCardOcr="idCardOcr"/>
        </el-form-item>
        <el-form-item prop="socialCreditCode" label="社会统一代码证">
          <el-input v-model="form.socialCreditCode" placeholder="请输入社会统一代码证号码" class="line-input"></el-input>
        </el-form-item>
        <el-form-item prop="businessLicenseNumber" label="营业执照注册号" v-if="form.certType !== 0">
          <el-input v-model="form.businessLicenseNumber" placeholder="请输入营业执照注册号码"
                    class="line-input"></el-input>
        </el-form-item>
        <el-form-item prop="organizationCode" label="组织机构代码证" v-if="form.certType !== 0">
          <el-input v-model="form.organizationCode" placeholder="请输入组织机构代码证号码" class="line-input"></el-input>
        </el-form-item>
        <el-form-item prop="businessLicenseName" label="营业执照名称">
          <el-input v-model="form.businessLicenseName" placeholder="请输入营业执照名称" class="line-input"></el-input>
        </el-form-item>

        <el-form-item prop="establishmentDate" label="成立日期">
          <el-date-picker
                  class="line-input"
                  v-model="form.establishmentDate"
                  type="date"
                  placeholder="成立日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="expirationDate" label="失效日期">
          <el-date-picker
                  class="line-input"
                  v-model="form.expirationDate"
                  type="date"
                  placeholder="失效日期">
          </el-date-picker>
        </el-form-item>

        <v-form-title title="企业信息"/>
        <el-form-item prop="enterpriseName" label="企业名称">
          <el-input class="line-input" v-model="form.enterpriseName" placeholder="请输入企业名称"></el-input>
        </el-form-item>
        <el-form-item prop="addressArray" label="通讯地址">
          <v-address ref="address" v-model="form.addressArray"></v-address>
        </el-form-item>
        <el-form-item prop="legalRepresentative" label="法定代表人姓名">
          <el-input class="line-input" v-model="form.legalRepresentative" placeholder="请输入法定代表人姓名"></el-input>
        </el-form-item>
        <el-form-item prop="legalCertType" label="法定代表人证件类型">
          <el-select v-model="form.legalCertType" placeholder="请选择法定代表人证件类型">
            <el-option
                    v-for="item in $dict.legalTypes"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="legalCertNo" label="法定代表人证件号码">
          <el-input class="line-input" v-model="form.legalCertNo" placeholder="请输入法定代表人证件号码"></el-input>
        </el-form-item>
        <el-form-item prop="legalAddressArray" label="法定代表人归属地">
          <v-address ref="legalAddressArray" v-model="form.legalAddressArray"></v-address>
        </el-form-item>
        <el-form-item prop="address" label="详细地址">
          <el-input class="line-input" v-model="form.address" placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item prop="industryType" label="行业类型">
          <el-select v-model="form.industryType" placeholder="请选择行业类型">
            <el-option
                    v-for="item in $dict.industryTypes"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="enterpriseType" label="企业类型">
          <el-select v-model="form.enterpriseType" placeholder="请选择企业类型">
            <el-option
                    v-for="item in $dict.enterpriseTypes"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属渠道商">
          {{form.affiliation}}
        </el-form-item>
        <el-form-item label="推荐人">
          {{form.recommendedManagerName}}
        </el-form-item>
      </el-form>
    </div>
    <div class="operation">
      <el-button type="primary" @click="valid">填写完毕下一步</el-button>
    </div>
  </div>
</template>
<script lang="ts">
  import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
  import { Action } from 'vuex-class'
  import vAddress from '@/components/address'
  import vUnitAuthImages from '@/components/unit-auth-images'
  import vFormTitle from '@/components/form-title'

  @Component({
    components: {
      vAddress,
      vUnitAuthImages,
      vFormTitle
    }
  })
  export default class Step1 extends Vue {
    next = true
    @Action getPolicy

    valid () {
      this.$refs['unit-auth'].valid()
    }

    post (form) {
      this.$emit('post', form)
    }

    @Prop() userInfo
    form = {
      certType: 0,
      socialCreditCode: '',
      businessLicenseNumber: '',
      businessLicenseName: '',
      establishmentDate: '',
      expirationDate: '',
      organizationCode: '',
      images: [],
      affiliation: '',
      recommendedManagerName: '',
      enterpriseUserId: '',
      //
      enterpriseName: '',
      addressArray: [],
      address: '',
      industryType: '',
      enterpriseType: '',
      legalRepresentative: '',
      legalCertNo: '',
      legalAddressArray: []
    }
    tempForm = {}
    rules = {
      certType: [{ required: true, message: '请选择营业执照类型', trigger: 'change' }],
      industryType: [{ required: true, message: '请选择行业类型', trigger: 'change' }],
      enterpriseType: [{ required: true, message: '请选择企业类型', trigger: 'change' }],
      socialCreditCode: [{ required: true, message: '请输入社会统一代码证号码', trigger: 'change' },
        {
          pattern: /(^(?:(?![IOZSV])[\dA-Z]){2}\d{6}(?:(?![IOZSV])[\dA-Z]){10}$)|(^\d{15}$)/,
          message: '证件号码错误',
          trigger: 'blur'
        }
      ],
      businessLicenseName: [{ required: true, message: '请输入营业执照名称\n', trigger: 'change' }],
      address: [{ required: true, message: '请输入详细地址', trigger: 'change' }],
      businessLicenseNumber: [{ required: true, message: '请输入营业执照注册号码', trigger: 'change' }],
      expirationDate: [{ required: true, message: '请选择失效日期', trigger: 'change' }],
      establishmentDate: [{ required: true, message: '请选择成立日期', trigger: 'change' }],
      organizationCode: [{ required: true, message: '请输入组织机构代码证号码', trigger: 'change' }],
      images: [{ type: 'array', required: true, message: '请上传相应的图片', trigger: 'change', len: 3 }],
      //
      enterpriseName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
      legalRepresentative: [{ required: true, message: '请输入法定代表人姓名', trigger: 'blur' }],
      legalCertNo: [{ required: true, message: '请输入法定代表人证件号码', trigger: 'blur' },
        {
          pattern: /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)/,
          message: '证件号码错误',
          trigger: 'blur'
        }],
      legalCertType: [{ required: true, message: '请输入法定代表人证件类型', trigger: 'blur' }],
      addressArray: [{ type: 'array', required: true, message: '请选择企业通讯地址', trigger: 'change', len: 3 }],
      legalAddressArray: [{ type: 'array', required: true, message: '请选择法定代表人归属地', trigger: 'change', len: 3 }]
    }

    imagesMap = [
      {
        key: 'businessLicensePhoto',
        src: '',
        name: '营业执照正本',
        placeholder: 'https://hpx-boss.oss-cn-qingdao.aliyuncs.com/fddde45b-2132-4e75-84ef-dcc983fe128b.png',
        certType: 0
      },
      {
        key: 'legalFrontPhoto',
        src: '',
        name: '法定代表人身份证正面',
        placeholder: 'https://hpx-boss.oss-cn-qingdao.aliyuncs.com/61afb7a6-904b-43fe-93f3-efc4f713cf08.png',
        certType: 0
      },
      {
        key: 'legalBackPhoto',
        src: '',
        name: '法定代表人身份证背面',
        placeholder: 'https://hpx-boss.oss-cn-qingdao.aliyuncs.com/f730fa6a-ca7b-4a57-9944-40b3c861fe29.png',
        certType: 0
      },
      {
        key: 'organizationCodePhoto',
        src: '',
        name: '组织机构代码证',
        placeholder: 'https://hpx-boss.oss-cn-qingdao.aliyuncs.com/2020d070-b61b-429f-99c2-3276572f2744.png',
        certType: 1
      },
      {
        key: 'taxRegistrationPhoto',
        src: '',
        name: '税务机构登记证',
        placeholder: 'https://hpx-boss.oss-cn-qingdao.aliyuncs.com/0fcef1e4-94e5-472e-b54e-6bf8d6f23592.png',
        certType: 2
      }
    ]

    get images () {
      return this.imagesMap.filter(image => this.form.certType >= image.certType)
    }

    valid () {
      this.$refs.form.validate(valid => {
        console.log(valid)
        if (!valid) return
        let f = { ...this.form }
        f.areaProvince = f.addressArray[0]
        f.areaCity = f.addressArray[1]
        f.areaDistrict = f.addressArray[2]
        f.legalProvince = f.legalAddressArray[0]
        f.legalCity = f.legalAddressArray[1]
        f.legalDistrict = f.legalAddressArray[2]
        f.channelProviderId = window.sessionStorage.getItem('enterpriseUserId')
        f.images.forEach(v => {
          f[v.key] = v.src
        })
        delete  f.images
        delete  f.addressArray
        delete  f.legalAddressArray
        for (let key in f) {
          if (f.hasOwnProperty(key)) {
            if (f[key] === null || f[key] === '') {
              delete f[key]
            }
          }
        }
        this.post(f)
      })
    }

    mounted () {
      this.getPolicy()
      let invite = JSON.parse(window.localStorage.getItem('invite'))
      if (invite) {
        this.form.affiliation = invite.affiliation
        this.form.recommendedManagerName = invite.managerName
        this.form.enterpriseUserId = invite.enterpriseUserId
      }
    }

    async licenseOcr (imageUrl) {
      let res: AjaxResponse = await this.$axios.post('g/gateway/ocr/business/license', {
        imageUrl
      })
      if (res.responseCode === 200) {
        this.form.address = res.data.address
        this.form.socialCreditCode = res.data.reg_num
        this.form.businessLicenseNumber = res.data.reg_num
        this.form.legalRepresentative = res.data.person
        this.form.establishmentDate = +new Date(res.data.establish_date.replace(/(.{4})/, '$1-').replace(/(.{7})/, '$1-'))
        this.form.expirationDate = +new Date(res.data.valid_period.replace(/(.{4})/, '$1-').replace(/(.{7})/, '$1-'))
        this.form.enterpriseName = res.data.name
        this.form.businessLicenseName = res.data.name
        if(res.data.reg_num !== undefined) {
            let strLength = (res.data.reg_num).length -1
            this.form.organizationCode = (res.data.reg_num).substring(8,strLength)
        }
      }
    }

    async idCardOcr (imageUrl) {
      let res: AjaxResponse = await this.$axios.post('g/gateway/ocr/idcard', {
        faceOrBack: 'face',
        imageUrl
      })
      if (res.responseCode === 200) {
        this.form.legalRepresentative = res.data.name
        this.form.legalCertNo = res.data.id_num
        // this.form.legalCertType = '1'
        this.form.address = res.data.address
      }
    }

    async post (form) {
      let res: AjaxResponse = await this.$axios.post('g/gateway/member/agencycertification', {
        ...form,
        establishmentDate: +form.establishmentDate,
        expirationDate: +form.expirationDate
      })
      window.sessionStorage.setItem('enterpriseName',this.form.enterpriseName)
      this.$utils.tips(res)
      if (res.responseCode === 200) {
        this.$router.push('/register/step-2')
      }
    }
  }
</script>
<style lang="less" scoped>
  .form-container {
    width: 1180px;
    margin: 0 auto;
    padding: 60px 0 30px;
  }

  .operation {
    text-align: center;
    font-size: 14px;
    color: #999;
    .el-button {
      margin: 30px 0;
    }
  }

  .el-steps {
    margin-bottom: 60px;
  }

  .el-select {
    width: 300px;
  }
</style>
